//路径别名
require("module-alias/register")
const { data } = require('@/utils/send')
const express = require("express");
const cors = require("cors");
const morgan = require("morgan")
const router = require("./router");
const app = express();
const db = require('@/database')
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cors());
// 自定义格式化函数  第一个参数就是自定义的格式化函数，第二个参数就是格式化函数返回的内容
morgan.token('body', (req, res) => JSON.stringify(req.body)); // 记录请求参数
morgan.token('query', (req, res) => JSON.stringify(req.query)); // 记录请求参数
morgan.token('response', (req, res) => JSON.stringify(res.locals.data)); // 记录返回值

const logger = morgan(':method :url :status :response-time ms - :query :body :response', {
    stream: process.stdout, // 输出到标准输出
})
app.use(logger)
app.use((req, res, next) => {
    res.cc = (err, code = 500) => {
        res.send({
            code,
            message: err instanceof Error ? err.message : err,
        });
    };
    next();
});
//路由
router(app);
//全局报错处理
app.use((err, req, res, next) => {
    console.log(req);
    if (err.name === "UnauthorizedError") {
        return res.send({
            code: 401,
            message: "无效的token",
        });
    }
    const datas = data({ code: 500, message: err instanceof Error ? err.message : err })
    res.send(datas);
    res.locals.data = datas;
    next();
});


app.listen(80, async () => {
    console.log("http://127.0.0.1");
    await db.sync({ alter: true });
});